<?php
$inst_id = MiscUtils::getParam('i', 0);

$cond_vals = new stdClass();
$cond_vals->c = 't.sys_id = :v1';
$cond_vals->v = array(':v1' => $system_id);
$opts = new stdClass();
$opts->select_expr = 't.id, t.parent_id, t.title, t.order, t.is_default, t.is_visible, t.sys_id';
$data->pages = DbUtils::get($myPdo, 'pz2_page', $cond_vals, 't.order', 'ASC', NULL, NULL, $opts)->d;
?>
<style>
.list {
  border-left: 1px solid #ddd;
  border-top: 1px solid #ddd;
}
.list td {
  vertical-align: middle;
  text-align: left;
  padding: 2px; 
  border-right: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}
.list td.nosort {
  background-color: #dababa;
  font-weight: bold;
}
.list tr.none td {
  background-color: #fff;
}
.list tr.current td {
  border-right: 1px solid #ff8000;
  border-bottom: 1px solid #ff8000;
  background-color: #ff8000;
}
.chrome {
  -webkit-appearance: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}
</style>
<div class="chrome">
<button onclick="parent.location.href='http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=page&tag=pages&sid=' . $system_id; ?>';">Create</button>
</div>
<table id="pages" class="list chrome" cellpadding=0 cellspacing=0>
  <tr>
    <td class="nosort" style="width: 500px;">Pages</td>
    <td class="nosort" style="width: 40px;">Home</td>
    <td class="nosort" style="width: 40px;">Visible</td>
    <td class="nosort" style="width: 60px;"></td>
  </tr>
</table>
<div class="chrome" style="height: 200px;">&nbsp;</div>
<script type="text/javascript" src="../../../incls/js/pageutils.js"></script>
<script type="text/javascript" src="../../../libs/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../../../incls/js/myutils.js"></script>
<script type="text/javascript">
  var _root = null;
  var _currentRow = null;
  var _options = [];
  var _count = 0;
  var _threadId = 0;
  
  $(function(){
    _root = PageUtils.getRoot(JSON.parse('<?php echo addslashes(json_encode($data->pages)); ?>'));
    setRoot('', false);
    document.body.onmouseup = function() {
      if (!_currentRow) {
        return;
      }
      $.ajax({
        type: 'POST',
        url: 'server.php',
        data: 'action=save&q=' + encodeURIComponent(JSON.stringify(_currentRow._node)),
        success: function(msg){
        }
      });
      _currentRow = null;
      setRoot('', false);
    };
  });

  function setRoot(prefix, is_child) {
    $('#pages').find('tr:gt(0)').remove();
    _setRoot(_root, $('#pages')[0], prefix, is_child);
  }

  function _setRoot(node, table, prefix, is_child) {
    var tr, td, elm;
    if (node.id != 0) {
      tr = table.insertRow(-1);
      tr._node = node;
      tr.className = 'none';
      if (_currentRow && _currentRow._node &&_currentRow._node.id == node.id || is_child) {
        tr.className = 'current';
        is_child = true;
        if (_currentRow && _currentRow._node &&_currentRow._node.id == node.id) {
          _currentRow = tr;
          tr.onmouseover = function() {
            transform();
          }
        }
      } else {
        tr.onmouseover = function() {
          if (_currentRow) {
            move(this);
          }
        }
      }
      
      td = tr.insertCell(-1);
      td.style.cursor = 'move';
      elm = document.createElement('a');
      td.appendChild(document.createTextNode(((prefix == '') ? '' : prefix + ') ' ) + ((node.id != 0 && node.title == '') ? 'Untitled' : node.title)));
      td.appendChild(elm);
      td.onmousedown = function() {
        _currentRow = tr;
        MyUtils.removeTableRows($('#pages')[0], 1);
        setRoot('', false);
      };
      td = tr.insertCell(-1);
      elm = document.createElement('input');
      elm.type = 'radio';
      elm.name = 'homepage';
      elm.checked = (node.is_default == 1) ? true : false;
      elm._node = node;
      elm.onclick = function() {
        this._node.is_default = this.checked ? 1 : 0;
        $.ajax({
          type: 'POST',
          url: '<?php echo basename(__FILE__, '.php'); ?>.server.php',
          data: 'action=save&q=' + encodeURIComponent(JSON.stringify(this._node)),
          success: function(msg){
          }
        });
      };
      td.appendChild(elm);
      td = tr.insertCell(-1);
      elm = document.createElement('input');
      elm.type = 'checkbox';
      elm.checked = (node.is_visible == 1) ? true : false;
      elm._node = node;
      elm.onclick = function() {
        this._node.is_visible = this.checked ? 1 : 0;
        $.ajax({
          type: 'POST',
          url: '<?php echo basename(__FILE__, '.php'); ?>.server.php',
          data: 'action=save&q=' + encodeURIComponent(JSON.stringify(this._node)),
          success: function(msg){
          }
        });
      };
      td.appendChild(elm);
      td = tr.insertCell(-1);
      elm = document.createElement('img');
      elm.src = 'assets/imgs/edit.png';
      elm.title = 'Edit';
      elm.style.cursor = 'pointer';
      elm.onclick = function() {
        parent.location.href = 'http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=page&tag=pages&sid=' . $system_id . '&pid='; ?>' + node.id;
      };
      td.appendChild(elm);

      elm = document.createElement('img');
      elm.src = 'assets/imgs/add.png';
      elm.title = 'Add subpage';
      elm.style.cursor = 'pointer';
      elm.style.marginLeft = '5px';
      elm.onclick = function() {
        parent.location.href = 'http://<?php echo URL . 'admin.php?i=' . $inst_id . '&part=page&tag=pages&sid=' . $system_id . '&parent_id='; ?>' + node.id;
      };
      td.appendChild(elm);
      
      elm = document.createElement('img');
      elm.src = 'assets/imgs/delete24.png';
      elm.title = 'Delete';
      elm.style.cursor = 'pointer';
      elm.style.marginLeft = '5px';
      elm._node = node;
      elm.onclick = function() {
        var r = window.confirm('Click OK to Proceed?');
        if (r) {
          $.ajax({
            type: 'POST',
            url: '<?php echo basename(__FILE__, '.php'); ?>.server.php',
            data: 'action=remove&q=' + encodeURIComponent(JSON.stringify(this._node)),
            success: function(msg){
              location.reload();
            }
          });
        }
      };
      td.appendChild(elm);
    } else if (node.id == 0 && node._children.length == 0) {
      tr = table.insertRow(-1);
      tr.className = 'none';
      td = tr.insertCell(-1);
      td.colSpan = 4;
      td.appendChild(document.createTextNode('None'));
    }
    for (var idx in node._children) {
      var obj = node._children[idx];
      _setRoot(obj, table, ((prefix == '') ? '(' : '\u2002' + prefix + '-' ) + (parseInt(idx, 10) + 1), is_child)
    }
  }

  function move(tr) {
    var params = PageUtils.getParams(_currentRow.rowIndex < tr.rowIndex, tr._node);
    _currentRow._node.parent_id = params.parent_id;
    _currentRow._node.order = params.order;
    PageUtils.update(_root);
    setRoot('', false);
  }

  function transform() {
    if (_threadId != 0) {
      clearTimeout(_threadId);
      _threadId = 0;
    }
    _options = [JSON.parse(JSON.stringify(_currentRow._node))];
    _travelOlders(_currentRow._node);
    _options.reverse();
    _count = _options.length - 1;
    var older = PageUtils.getOlder(_root, _currentRow._node);
    if (older) {
      _travelYounger(older, _options)
    }
    _threadId = setTimeout('_transform();', 1000);
    
  }

  function _transform() {
    if (_threadId != 0) {
      clearTimeout(_threadId);
      _threadId = 0;
    }
    if (_currentRow == null) {
      return;
    }
    _count++;
    _count = _count % _options.length;
    var option = _options[_count];
    _currentRow._node.parent_id = option.parent_id;
    _currentRow._node.order = option.order;
    PageUtils.update(_root);
    setRoot('', false);
    _threadId = setTimeout('_transform();', 1000);
  }

  function _travelOlders(node) {
    var younger = PageUtils.getYounger(_root, node);
    if (younger || node.parent_id == 0) {
      return;
    }
    var parent = PageUtils.getById(_root, node.parent_id);
    _options[_options.length] = PageUtils.getParams(1, parent)
    _travelOlders(parent);
  }
  
  function _travelYounger(node) {
    if (node._children.length == 0) {
      _options[_options.length] = {
        parent_id: node.id,
        order: 0
      }
      return;
    }
    var child = node._children[node._children.length - 1];
    _options[_options.length] = PageUtils.getParams(1, child)
    _travelYounger(child)
  }
</script>